package io.ydjs.service.password.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.ydjs.common.exception.YdjsException;
import io.ydjs.common.utils.EncryptionUtil;
import io.ydjs.service.password.dao.PasswordDao;
import io.ydjs.service.password.entity.PasswordEntity;
import io.ydjs.service.password.service.PasswordService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("passwordService")
public class PasswordServiceImpl extends ServiceImpl<PasswordDao, PasswordEntity> implements PasswordService {

    private static final Integer MAX_FAILED_COUNT = 5;

    @Override
    public void verifyPassword(String mobileNo, String password) {
        LambdaQueryWrapper<PasswordEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PasswordEntity::getMobileNo, mobileNo);
        PasswordEntity passwordEntity = this.getOne(wrapper);

        if(passwordEntity == null){
            throw new YdjsException("账号不存在");
        }

        if(passwordEntity.getFailedCount() >= MAX_FAILED_COUNT){
            String resetTime = "5";
            if (passwordEntity.getResetTime() != null) {
                long begTime = passwordEntity.getResetTime().getTime();
                long endTime = new Date().getTime();
                long l = endTime - begTime;
                if (l > 300000) {
                    passwordEntity.setFailedCount(0);
                    this.updateById(passwordEntity);
                }else {
                    resetTime = String.valueOf((l / 60000) % 60);
                    throw new YdjsException("错误次数达到上限,请"+resetTime+"分钟再试");
                }
            }else {
                passwordEntity.setResetTime(new Date());
                this.updateById(passwordEntity);
                throw new YdjsException("错误次数达到上限,请"+resetTime+"分钟再试");
            }
        }

        if(!EncryptionUtil.encodeBase64(password).equals(passwordEntity.getPassword())){
            throw new YdjsException("密码错误");
        }
    }

    @Override
    public void login(String mobileNo) {
        LambdaQueryWrapper<PasswordEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PasswordEntity::getMobileNo, mobileNo);
        PasswordEntity passwordEntity = this.getOne(wrapper);
        if(passwordEntity != null){
            throw new YdjsException("账号已存在");
        }
    }
}